package com.sk.bilibili.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sk.bilibili.dto.AppraiseInfo;
import com.sk.bilibili.event.BiliBiliEvent;
import com.sk.bilibili.other.R;
import com.sk.bilibili.utils.BSessionUtils;
import com.sk.bilibili.utils.QueryWrapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import com.sk.bilibili.bean.Appraise;
import com.sk.bilibili.mapper.AppraiseMapper;

/**
 * @author 邵康
 * @date 2021/12/03 23:09
 */
@Service
public class AppraiseService extends ServiceImpl<AppraiseMapper, Appraise> {

    @Autowired
    private MemberService memberService;
    @Autowired
    private PraiseService praiseService;
    @Autowired
    private ApplicationEventPublisher eventPublisher;

    public R<Void> add(Appraise appraise) {
        appraise.setMemberId(BSessionUtils.getMemberId());
        save(appraise);
        eventPublisher.publishEvent(new BiliBiliEvent<>(this, appraise));
        return R.success();
    }

    public R<Void> delete(Integer id) {
        removeById(id);
        return R.success();
    }

    public R<Void> update(Appraise appraise) {
        eventPublisher.publishEvent(new BiliBiliEvent<>(this, appraise));
        updateById(appraise);
        return R.success();
    }

    public R<Appraise> getAppraise(Integer themId) {
        int memberId = BSessionUtils.getMemberId();
        Appraise appraise = getAppraise(themId, memberId);
        warpAppraise(appraise);
        return R.success(appraise);
    }

    private void warpAppraise(Appraise appraise) {
        if (appraise == null) return;
        appraise.getExtra().addExtra(memberService.getById(appraise.getMemberId()));
        appraise.getExtra().put("praise", praiseService.hasPraise(appraise.getMemberId(), 4, appraise.getId()));
    }

    public Appraise getAppraise(Integer themId, int memberId) {
        QueryWrapper<Appraise> queryWrapper = QueryWrapperUtils.eq("them_id", themId,
                "member_id", memberId);
        return getOne(queryWrapper);
    }

    public R<IPage<Appraise>> page(AppraiseInfo appraiseInfo) {
        QueryWrapper<Appraise> queryWrapper = QueryWrapperUtils.eq("them_id", appraiseInfo.getThemId());
        if (appraiseInfo.getSort() != null) queryWrapper.orderByDesc(appraiseInfo.getColumn());
        IPage<Appraise> page = page(appraiseInfo.page(), queryWrapper);
        page.getRecords().forEach(this::warpAppraise);
        return R.success(page);
    }

}
